package com.scs.application.modules.dept.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.mvc.controller.FlowController;
import com.scs.application.modules.dept.dto.DemandSumDTO;
import com.scs.application.modules.dept.entity.DemandSum;
import com.scs.application.modules.dept.entity.DemandSumItem;
import com.scs.application.modules.dept.service.DemandSumItemService;
import com.scs.application.modules.dept.service.DemandSumService;
import com.scs.application.modules.sys.model.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.Serializable;

/**
 * <p>
 *  前端控制器
 * </p>
 */
@RestController
@RequestMapping("/dept/demand_sum")
public class DemandSumController extends FlowController<DemandSumService, DemandSum> {
    @Autowired
    private DemandSumItemService demandSumItemService;

    @PostMapping("addByDemand")
    public RestResult addByTemp(@RequestBody DemandSumDTO demandSumDTO) {
        return RestResult.ok("OK", service.addByDemand(demandSumDTO));
    }

    private void fillEntity(DemandSum entity) {
        entity.setCountDtl(demandSumItemService.count(Wrappers.<DemandSumItem>query().select("id").eq("demand_sum_id",entity.getId())));
    }

    /**
     * 根据ID查找数据
     */
    @GetMapping("/find")
    public RestResult find(@RequestParam("id") Serializable id) {
        DemandSum entity = service.getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        fillEntity(entity);
        return RestResult.ok("获取数据成功", entity);
    }


    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody DemandSum entity) {
        boolean isOk = service.saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        fillEntity(entity);
        return RestResult.ok("数据保存成功", entity);
    }
}
